<template>
  <el-dialog
    :title="data.titleMap[data.mode]"
    :width="500"
    v-model="data.visible"
  >
    <!-- 表单 -->
    <el-form
      :model="data.form"
      :rules="data.rules"
      ref="dialogForm"
      label-width="100px"
      label-position="left"
      v-loading="data.loading"
    >
      <el-form-item label="流程类型名称" prop="processCategoryName">
        <el-input v-model="data.form.processCategoryName" clearable></el-input>
      </el-form-item>
      <el-form-item label="流程类型Key" prop="processCategoryKey">
        <el-input v-model="data.form.processCategoryKey" clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="data.visible = false">取 消</el-button>
      <el-button type="primary" :loading="data.isSaveing" @click="submit()">
        保 存
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref } from 'vue';
//引入添加的接口
import Api from '@/api/flow/processCategory';
import { ElMessageBox, ElMessage } from 'element-plus';
//定义子组件的ref
let dialogForm = ref();
let emit: any = defineEmits();
const data = reactive<any>({
  mode: 'add',
  titleMap: {
    edit: '编辑',
    add: '新增',
  },
  visible: false,
  isSaveing: false,
  //表单数据
  form: {
    processCategoryName: '',
    processCategoryKey: '',
    id: '',
  },
  roleId: '',
  loading: false,
  //验证规则
  rules: {
    number: [
      {
        required: true,
        message: '请输入排序',
        trigger: 'change',
      },
    ],
    name: [{ required: true, message: '请输入角色名称' }],
    remark: [{ required: true, message: '请输入角色说明' }],
  },
  //所需数据选项
  groups: [],
  groupsProps: {
    value: 'id',
    emitPath: false,
    checkStrictly: true,
  },
});
//子组件的打开方法
const open = (mode = 'add', id = '') => {
  if (mode != 'add') {
    setData(id);
  }

  data.mode = mode;
  data.visible = true;

  return data;
};
//表单提交方法
const submit = async () => {
  dialogForm.value.validate(async (valid: any) => {
    if (valid) {
      data.isSaveing = true;
      var res = await Api.save.post(data.form);
      data.isSaveing = false;
      if (res.code == 0) {
        //回调函数
        emit('success', data.form, data.mode);
        data.visible = false;
        ElMessage.success('操作成功!');
      } else {
        ElMessageBox.alert(res.message, '提示', { type: 'error' });
      }
    }
  });
};
const getRoleData = async (id: string) => {
  const res = await Api.getRoleById.get(id);
  if (res != null && res.code == 0) {
    data.form = res.data;
  } else {
    ElMessage.error('获取数据失败!');
  }
};

//表单注入数据
const setData = (id: string) => {
  data.form.id = id;
  // 请求数据
  getRoleData(id);
  //可以和上面一样单个注入，也可以像下面一样直接合并进去
  //Object.assign(this.form, data)
};
//defineExpose 子组件暴露方法
defineExpose({ open, setData });
</script>
